<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use fast\Random;
use think\Db;

set_time_limit(0);
/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;

    /**
     * User模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $map['parent_id'] = 0;
            // 判断是不是超级管理员
            if ( !$this->auth->isSuperAdmin() ){
                $map['admin_id'] = $this->auth->id;
            }

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = $this->request->get("filter", '');
            $filter = json_decode($filter, TRUE);
             $filter = $filter ? $filter : [];

            if ( !isset($filter['status']) ){
                $map['user.status'] = 'normal';
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with('group')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $userList = \app\admin\model\User::where('parent_id', 0)->where('id', 'neq', $row['id'])->column('id,username');
        $userList[0] = "无";

        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign('userList', build_select('row[parent_id]', $userList, $row['parent_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
//                $params['avatar'] = '/uploads/20180415/90ab4868b9a1983488e9040713835220.jpg'; //设置新管理员默认头像。
                $params['admin_id'] = $this->auth->id;
                $params['status'] = 'normal';
                $params['parent_id'] = $params['parent_id'];
                $result = $this->model->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }

        $map['parent_id'] = 0;
        if ( !$this->auth->isSuperAdmin() ){
            $map['admin_id'] = $this->auth->id;
        }


        $userList = \app\admin\model\User::where($map)->column('id,username');
        $userList[0] = "无";

        $this->view->assign('userList', build_select('row[parent_id]', $userList, 0, ['class' => 'form-control selectpicker']));
        return $this->view->fetch();
    }

    public function pt()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 积分管理
     **/
    public function score($ids = "")
    {
        // 获取数据
        $row = $this->model->where('id', $ids)->value('score');
        if (!$row){
            $row = 0;
        }

        // 修改积分
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            if ((int)$params['score'] == 0){
                $this->error('不能等于0');
            }else if ((int)$params['score'] > 0){
                $type = 2;
                $row += (int)$params['score'];
            }else{
                $type = 3;
                $row -= abs((int)$params['score']);
            }

            $result = $this->model->allowField(['score'])->where('id', $ids)->setInc('score', (int)$params['score']);

            // 积分详情
            $addScore = [
                'user_id'=>$ids,
                'residue'=>$row,
                'score'=>(int)$params['score'],
                'type'=>$type,
                'msg'=>'购买客户',
                'admin_id'=>$this->auth->id,
                'create_time'=>time()
            ];

            db('score_detail')->insert($addScore);

            if ($result === false) {
                $this->error($this->model->getError());
            }

            $this->success();
        }

        $this->assign('score', $row);
        return $this->view->fetch();

    }


    /**
     * 读取树状
     *
     **/
    public function roletree()
    {
        //是否是超级管理员
        $superadmin = $this->auth->isSuperAdmin();
        if ($superadmin) {
            $map['parent_id'] = 0;
        } else {
            $map['parent_id'] = $this->auth->id;
        }

        $ret = $this->model->where($map)->field('id,username,parent_id')->select();
        $nodeList = [];
        if ($ret) {
            foreach ($ret as $v) {
                $nodeList[] = array('id' => $v['id'], 'parent' => $v['parent_id'] ? $v['parent_id'] : '#', 'text' => $v['username'], 'type' => 'menu');
            }
            $this->success('', null, $nodeList);
        } else {
            $this->error('暂无数据');

        }
    }

    /**
     * 查看详情
     **/
    public function detail()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $map = [];

            // 判断是不是超级管理员
            if ( !$this->auth->isSuperAdmin() ){
                $map['admin_id'] = $this->auth->id;
            }

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = $this->request->get("filter", '');
            $filter = json_decode($filter, TRUE);
            $filter = $filter ? $filter : [];

            if ( !isset($filter['status']) ){
                $map['user.status'] = 'normal';
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with('group')
                ->where($map)
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($map)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 修改状态
    **/
    public function status($ids){

        if ( $ids ){
            if ($this->request->isAjax()){
                $map['id'] = $ids;

                // 判断是不是超级管理员
                if ( !$this->auth->isSuperAdmin() ){
                    $map['admin_id'] = $this->auth->id;
                }

                $ret = $this->model->where($map)->update(['status'=>'hidden']);
                if ( $ret ){
                    $this->success('删除成功');
                }else{
                    $this->success('删除失败');
                }
            }
        }else{
            $this->error('id为空');
        }


    }


    /**
     * 购买
     **/
    public function order(){

        // 进件数量
        $id = input('ids/d',0);
        $user = model('user');
        $Bet = model('ApplyBet');
        $user2 = $user->get($id);

        if (!$user2){
            $this->error('用户不存在');
        }

        // 今日注册量
        $RegNumber = $Bet->dayreg($id);

        if ($this->request->isAjax()){

            $number = input('number/d',0);

            if (!$number){
                $this->error('数量不能为空');
            }

            if ( !$id ){
                $this->error('id不能为空');
            }

            if ( $user->where(['id'=>$id])->update(['into_the_number'=>$number]) ){
                $this->success('设置成功');
            }else{
                $this->error('设置失败');
            }
        }

        return $this->view->fetch('',['total'=>$RegNumber->total,'into_the_number'=>$user2->into_the_number]);

    }

    /**
     * 购买记录
    **/
    public function bet(){
        return $this->view->fetch();
    }

}
